# -*- coding: utf-8 -*-
"""
心理咨询师服务系统 - 用户API
"""

from flask import request, jsonify, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity, create_access_token
from app.api.users import bp
from app.models import User, UserBasicInfo, UserMembership
from app import db
from app.utils.validators import validate_email, validate_phone
from app.utils.helpers import success_response, error_response
from datetime import datetime
import re


@bp.route('/profile', methods=['GET'])
@jwt_required()
def get_user_profile():
    """获取用户资料"""
    try:
        user_id = get_jwt_identity()
        user = User.query.get(user_id)
        
        if not user:
            return error_response('用户不存在', 404)
        
        # 获取用户基本信息
        basic_info = UserBasicInfo.query.filter_by(user_id=user_id).first()
        
        # 获取会员信息
        membership = UserMembership.query.filter_by(user_id=user_id).first()
        
        profile_data = {
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'phone': user.phone,
            'avatar': user.avatar,
            'status': user.status.value,
            'created_at': user.created_at.isoformat() if user.created_at else None,
            'last_login_at': user.last_login_at.isoformat() if user.last_login_at else None,
            'basic_info': {
                'real_name': basic_info.real_name if basic_info else None,
                'gender': basic_info.gender.value if basic_info and basic_info.gender else None,
                'birth_date': basic_info.birth_date.isoformat() if basic_info and basic_info.birth_date else None,
                'occupation': basic_info.occupation if basic_info else None,
                'education': basic_info.education if basic_info else None,
                'location': basic_info.location if basic_info else None,
                'bio': basic_info.bio if basic_info else None
            },
            'membership': {
                'is_member': membership.is_active if membership else False,
                'member_type': membership.member_type.value if membership and membership.member_type else None,
                'expires_at': membership.expires_at.isoformat() if membership and membership.expires_at else None
            }
        }
        
        return success_response('获取用户资料成功', profile_data)
        
    except Exception as e:
        current_app.logger.error(f'获取用户资料失败: {str(e)}')
        return error_response('获取用户资料失败')


@bp.route('/profile', methods=['PUT'])
@jwt_required()
def update_user_profile():
    """更新用户资料"""
    try:
        user_id = get_jwt_identity()
        user = User.query.get(user_id)
        
        if not user:
            return error_response('用户不存在', 404)
        
        data = request.get_json()
        
        # 更新用户基本信息
        if 'email' in data:
            email = data['email'].strip()
            if not validate_email(email):
                return error_response('邮箱格式不正确')
            
            # 检查邮箱是否已被使用
            existing_user = User.query.filter(User.email == email, User.id != user_id).first()
            if existing_user:
                return error_response('邮箱已被使用')
            
            user.email = email
        
        if 'phone' in data:
            phone = data['phone'].strip()
            if phone and not validate_phone(phone):
                return error_response('手机号格式不正确')
            
            # 检查手机号是否已被使用
            if phone:
                existing_user = User.query.filter(User.phone == phone, User.id != user_id).first()
                if existing_user:
                    return error_response('手机号已被使用')
            
            user.phone = phone
        
        if 'avatar' in data:
            user.avatar = data['avatar']
        
        # 更新用户详细信息
        basic_info = UserBasicInfo.query.filter_by(user_id=user_id).first()
        if not basic_info:
            basic_info = UserBasicInfo(user_id=user_id)
            db.session.add(basic_info)
        
        basic_info_data = data.get('basic_info', {})
        
        if 'real_name' in basic_info_data:
            basic_info.real_name = basic_info_data['real_name']
        
        if 'gender' in basic_info_data:
            from app.models.user import Gender
            try:
                basic_info.gender = Gender(basic_info_data['gender'])
            except ValueError:
                return error_response('性别值不正确')
        
        if 'birth_date' in basic_info_data:
            try:
                birth_date = datetime.fromisoformat(basic_info_data['birth_date']).date()
                basic_info.birth_date = birth_date
            except ValueError:
                return error_response('出生日期格式不正确')
        
        if 'occupation' in basic_info_data:
            basic_info.occupation = basic_info_data['occupation']
        
        if 'education' in basic_info_data:
            basic_info.education = basic_info_data['education']
        
        if 'location' in basic_info_data:
            basic_info.location = basic_info_data['location']
        
        if 'bio' in basic_info_data:
            basic_info.bio = basic_info_data['bio']
        
        user.updated_at = datetime.utcnow()
        db.session.commit()
        
        return success_response('更新用户资料成功')
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'更新用户资料失败: {str(e)}')
        return error_response('更新用户资料失败')


@bp.route('/change-password', methods=['POST'])
@jwt_required()
def change_password():
    """修改密码"""
    try:
        user_id = get_jwt_identity()
        user = User.query.get(user_id)
        
        if not user:
            return error_response('用户不存在', 404)
        
        data = request.get_json()
        old_password = data.get('old_password')
        new_password = data.get('new_password')
        
        if not old_password or not new_password:
            return error_response('请提供旧密码和新密码')
        
        # 验证旧密码
        if not user.check_password(old_password):
            return error_response('旧密码不正确')
        
        # 验证新密码强度
        if len(new_password) < 6:
            return error_response('新密码长度至少6位')
        
        # 设置新密码
        user.set_password(new_password)
        user.updated_at = datetime.utcnow()
        db.session.commit()
        
        return success_response('密码修改成功')
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'修改密码失败: {str(e)}')
        return error_response('修改密码失败')


@bp.route('/assessments', methods=['GET'])
@jwt_required()
def get_user_assessments():
    """获取用户测评记录"""
    try:
        user_id = get_jwt_identity()
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        status = request.args.get('status')
        
        # 构建查询
        from app.models import Assessment
        query = Assessment.query.filter_by(user_id=user_id)
        
        if status:
            from app.models.assessment import AssessmentStatus
            try:
                query = query.filter_by(status=AssessmentStatus(status))
            except ValueError:
                return error_response('状态参数不正确')
        
        # 分页查询
        assessments = query.order_by(Assessment.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        assessment_list = []
        for assessment in assessments.items:
            assessment_data = {
                'id': assessment.id,
                'scale_id': assessment.scale_id,
                'scale_title': assessment.scale.title if assessment.scale else None,
                'status': assessment.status.value,
                'progress_percentage': assessment.progress_percentage,
                'started_at': assessment.started_at.isoformat() if assessment.started_at else None,
                'completed_at': assessment.completed_at.isoformat() if assessment.completed_at else None,
                'time_spent': assessment.time_spent
            }
            assessment_list.append(assessment_data)
        
        result = {
            'assessments': assessment_list,
            'pagination': {
                'page': assessments.page,
                'pages': assessments.pages,
                'per_page': assessments.per_page,
                'total': assessments.total,
                'has_next': assessments.has_next,
                'has_prev': assessments.has_prev
            }
        }
        
        return success_response('获取测评记录成功', result)
        
    except Exception as e:
        current_app.logger.error(f'获取用户测评记录失败: {str(e)}')
        return error_response('获取测评记录失败')


@bp.route('/delete-account', methods=['POST'])
@jwt_required()
def delete_account():
    """删除账户"""
    try:
        user_id = get_jwt_identity()
        user = User.query.get(user_id)
        
        if not user:
            return error_response('用户不存在', 404)
        
        data = request.get_json()
        password = data.get('password')
        
        if not password:
            return error_response('请提供密码确认')
        
        # 验证密码
        if not user.check_password(password):
            return error_response('密码不正确')
        
        # 软删除用户
        from app.models.user import UserStatus
        user.status = UserStatus.DELETED
        user.deleted_at = datetime.utcnow()
        user.updated_at = datetime.utcnow()
        
        # 可以选择删除相关数据或保留用于审计
        # 这里选择保留数据但标记为已删除
        
        db.session.commit()
        
        return success_response('账户删除成功')
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'删除账户失败: {str(e)}')
        return error_response('删除账户失败')